package com.bupt.ilink.service.innovationPlaza;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bupt.ilink.entity.innovationPlaza.*;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsIntroduceResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsMembersResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsMetaResponse;
import com.bupt.ilink.mapper.innovationPlaza.*;
//import jakarta.transaction.Transactional;
import com.bupt.ilink.service.MinioService;
import com.bupt.ilink.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;


@Service
public class ProjectService {

    @Autowired
    private InnovationPlazaMapper innovationPlazaMapper;

    @Autowired
    private ProjectMetadataMapper projectMetadataMapper;

    @Autowired
    private OssService ossService;

    @Autowired
    private ProjectConnectImageMapper projectConnectImageMapper;

    @Autowired
    private InnovationPlazaImageMapper innovationPlazaImageMapper;

    @Autowired
    private InnovationTagsMapper innovationTagsMapper;

    @Autowired
    private InnovationConnectTagsMapper innovationConnectTagsMapper;

    @Autowired
    private UserMetadataMapper userMetadataMapper;

    @Autowired
    private ProjectUserMapper projectUserMapper;

    @Autowired
    private UserLikeMapper userLikeMapper;

    public List<InnovationTags> getCommonTags() { return innovationTagsMapper.selectCommonProjectTags(); }

    public IPage<ProjectResponse> getALLProjects(
            String sentence,
            List<String> tags,
            String sortBy,
            int pageNum,
            int pageSize,
            String userId,
            Integer projectStyle) {

        // 1. 获取符合条件的记录总数，用于计算 total 和 pages
        QueryWrapper<ProjectMetadata> queryWrapper = new QueryWrapper<>();

        if (projectStyle != null) {
            queryWrapper.eq("project_style", projectStyle);
        }

        if (tags != null && !tags.isEmpty()) {
            // 根据标签条件加入查询条件
            List<Long> projectIds = innovationTagsMapper.getProjectIdsByTags(tags);
            if (!projectIds.isEmpty()) {
                queryWrapper.in("project_id", projectIds);
            } else {
                // 如果没有符合条件的项目，直接返回空分页
                return new Page<>(pageNum, pageSize, 0);
            }
        }

        if (sentence != null && !sentence.isEmpty()) {
            queryWrapper.like("name", sentence);
        }

        // 获取总记录数
        long totalRecords = projectMetadataMapper.selectCount(queryWrapper);

        // 2. 获取当前页的数据详情
        Page<ProjectMetadata> pageRequest = new Page<>(pageNum, pageSize);
        IPage<ProjectMetadata> projectMetadataPage = projectMetadataMapper.selectPage(pageRequest, queryWrapper);
        List<ProjectMetadata> projectMetadatas = projectMetadataPage.getRecords();

        List<ProjectResponse> projectResponses = new ArrayList<>();

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        try {
            // 使用线程池并行处理每个项目的额外信息
            List<Future<ProjectResponse>> futures = projectMetadatas.stream()
                    .map(projectMetadata -> executorService.submit(() -> {
                        ProjectResponse projectResponse = new ProjectResponse();
                        projectResponse.setProjectId(projectMetadata.getProjectId());
                        projectResponse.setName(projectMetadata.getName());
                        projectResponse.setCreatedTime(projectMetadata.getCreatedTime());

                        Integer style = projectMetadata.getProjectStyle();
                        projectResponse.setProjectStyle(style != null ? style : 0);

                        // 设置 description, likeNum, shareNum, lookNum
                        projectResponse.setDescription(projectMetadata.getDescription());
                        projectResponse.setLikeNum(projectMetadata.getLikeNum());
                        projectResponse.setShareNum(projectMetadata.getShareNum());
                        projectResponse.setLookNum(projectMetadata.getLookNum());

                        // 使用你提供的方法获取项目的标签
                        List<String> projectTags = innovationTagsMapper.getTagsByProjectId(projectMetadata.getProjectId());
                        projectResponse.setTags(projectTags);

                        int count = userLikeMapper.countUserLike(projectMetadata.getProjectId(), userId);
                        projectResponse.setLikeTrue(count > 0);

                        String projectImageRelativePath = projectMetadata.getProjectImage();
                        if (projectImageRelativePath != null && !projectImageRelativePath.isEmpty()) {
                            String projectImageUrl = ossService.getFileUrl(projectImageRelativePath);
                            projectResponse.setImage(projectImageUrl);
                        } else {
                            projectResponse.setImage("");
                        }

                        List<Long> imageIds = projectConnectImageMapper.getImageIdsByProjectId(projectMetadata.getProjectId());

                        List<String> projectImages = imageIds.stream()
                                .map(imageId -> {
                                    String imagePath = innovationPlazaImageMapper.selectById(imageId).getImage();
                                    return imagePath != null && !imagePath.isEmpty() ? ossService.getFileUrl(imagePath) : null;
                                })
                                .filter(Objects::nonNull)
                                .collect(Collectors.toList());

                        projectResponse.setProjectImages(projectImages);

                        return projectResponse;
                    })).collect(Collectors.toList());

            // 获取处理后的项目列表
            projectResponses = futures.stream()
                    .map(future -> {
                        try {
                            return future.get();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }).collect(Collectors.toList());

        } finally {
            executorService.shutdown();
        }

        // 进行排序（如果有必要）
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdtime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
            }
        }

        // 构建最终分页结果
        Page<ProjectResponse> finalPage = new Page<>(pageNum, pageSize, totalRecords);
        finalPage.setRecords(projectResponses);

        return finalPage;
    }
















/*    //查看大创项目的概览
    public IPage<ProjectResponse> getALLProjects(String sentence, List<String> tags, String sortBy, int pageNum, int pageSize, String userId) {
        // 创建分页对象
        Page<ProjectResponse> page = new Page<>(pageNum, pageSize);

        // 查询项目元数据并分页
        IPage<ProjectResponse> projectResponsesPage = projectMetadataMapper.getAllProjectMetaPage(page);

        List<ProjectResponse> projectResponses = projectResponsesPage.getRecords();

        for (ProjectResponse projectResponse : projectResponses) {
            // 获取项目标签并设置
            List<String> projectTags = innovationTagsMapper.getTagsByProjectId(projectResponse.getProjectId());
            projectResponse.setTags(projectTags);

            // 获取收藏状态
            int count = userLikeMapper.countUserLike(projectResponse.getProjectId(), userId);
            projectResponse.setLikeTrue(count > 0);

            // 设置 image 字段
            ProjectMetadata projectMetadata = projectMetadataMapper.selectById(projectResponse.getProjectId());
            projectResponse.setImage(projectMetadata.getProjectImage());

            // 获取并设置 projectImages 字段
            List<Long> imageIds = projectConnectImageMapper.getImageIdsByProjectId(projectResponse.getProjectId());
            List<String> images = imageIds.stream()
                    .map(imageId -> innovationPlazaImageMapper.selectById(imageId).getImage())
                    .collect(Collectors.toList());
            projectResponse.setProjectImages(images);
        }

        // 根据sortBy参数进行排序
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdtime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
            }
        }

        if (tags.contains("全部")) {
            // 将 tags 修改为空列表
            tags.clear();
        }

        // 按需过滤项目
        List<ProjectResponse> filteredProjects = projectResponses;
        boolean filterByTags = tags != null && !tags.isEmpty();
        boolean filterBySentence = sentence != null && !sentence.isEmpty();

        if (filterByTags) {
            // 根据标签进行过滤
            filteredProjects = filteredProjects.stream()
                    .filter(project -> project.getTags() != null && !project.getTags().isEmpty() && new HashSet<>(project.getTags()).containsAll(tags))
                    .collect(Collectors.toList());
        }

        if (filterBySentence) {
            // 进行模糊查询过滤
            filteredProjects = filteredProjects.stream()
                    .filter(project -> project.getName() != null && project.getName().contains(sentence))
                    .collect(Collectors.toList());
        }

        if (filterByTags && filterBySentence) {
            // 同时过滤标签和模糊查询
            filteredProjects = projectResponses.stream()
                    .filter(project -> project.getTags() != null && !project.getTags().isEmpty() && new HashSet<>(project.getTags()).containsAll(tags))
                    .filter(project -> project.getName() != null && project.getName().contains(sentence))
                    .collect(Collectors.toList());
        }

        // 设置过滤后的数据到分页对象中
        page.setRecords(filteredProjects);
        page.setTotal(filteredProjects.size());

        return page;
    }*/



    public List<ProjectResponse> getAllProjectMeta(String sortBy) {
        List<ProjectResponse> projectResponses = projectMetadataMapper.getAllProjectMeta();
        for (ProjectResponse projectResponse : projectResponses) {
            List<String> tags = innovationTagsMapper.getTagsByProjectId(projectResponse.getProjectId());
            projectResponse.setTags(tags);
        }
        // 根据sortBy参数进行排序
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdTime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    break;
            }
        }

        return projectResponses;
    }
    public IPage<ProjectResponse> getAllProjectMetaPage(String sortBy, int pageNum, int pageSize) {
        // 创建分页对象
        Page<ProjectResponse> page = new Page<>(pageNum, pageSize);

        // 查询项目元数据并分页
        IPage<ProjectResponse> projectResponsesPage = projectMetadataMapper.getAllProjectMetaPage(page);

        List<ProjectResponse> projectResponses = projectResponsesPage.getRecords();

        // 获取每个项目的标签并设置
        for (ProjectResponse projectResponse : projectResponses) {
            List<String> tags = innovationTagsMapper.getTagsByProjectId(projectResponse.getProjectId());
            projectResponse.setTags(tags);
        }

        // 根据sortBy参数进行排序
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdTime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    break;
            }
        }

        // 设置排序后的数据
        projectResponsesPage.setRecords(projectResponses);

        return projectResponsesPage;
    }
    //直接用sql做的查询，tags结果未知
    public List<ProjectResponse> getAllProjectDetails() {
        return projectMetadataMapper.getAllProjectDetails();
    }
    //基于标签的筛选查询
    public IPage<ProjectResponse> searchProjectsByTags(List<String> tags, String sortBy, int pageNum, int pageSize) {
        // 创建分页对象
        Page<ProjectResponse> page = new Page<>(pageNum, pageSize);

        // 查询项目元数据并分页
        IPage<ProjectResponse> projectResponsesPage = projectMetadataMapper.getAllProjectMetaPage(page);

        List<ProjectResponse> projectResponses = projectResponsesPage.getRecords();

        // 获取每个项目的标签并设置
        for (ProjectResponse projectResponse : projectResponses) {
            List<String> projectTags = innovationTagsMapper.getTagsByProjectId(projectResponse.getProjectId());
            projectResponse.setTags(projectTags);
        }

        // 根据sortBy参数进行排序
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdTime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    break;
            }
        }

        // 根据标签进行过滤
        List<ProjectResponse> filteredProjects = projectResponses.stream()
                .filter(project -> project.getTags() != null && !project.getTags().isEmpty() && new HashSet<>(project.getTags()).containsAll(tags))
                .collect(Collectors.toList());

        // 将过滤后的数据设置回分页对象中
        page.setRecords(filteredProjects);
        page.setTotal(filteredProjects.size());

        return page;
    }

    // 查看大创项目的详细信息

    // 获取详细页面的基础元信息
    public ProjectdetailsMetaResponse getProjectDetailsMeta(Long projectId) {
        ProjectdetailsMetaResponse response = new ProjectdetailsMetaResponse();

        // 获取项目名称
        String projectName = projectMetadataMapper.getProjectNameById(projectId);
        response.setName(projectName);

        // 获取项目标签
        List<String> tags = innovationTagsMapper.getTagsByProjectId(projectId);
        response.setTags(tags);

        // 获取项目风格
        Integer projectStyle = projectMetadataMapper.getProjectStyleById(projectId);
        response.setProjectStyle(String.valueOf(projectStyle));

        // 根据项目风格设置不同的字段
        if (projectStyle != null) {
            switch (projectStyle) {
                case 1:
                    // 获取口号
                    String advertise = projectMetadataMapper.getSloganByProjectId(projectId);
                    response.setAdvertise(advertise);
                    break;
                case 2:
                    // 获取公司名称
                    String company = projectMetadataMapper.getCompanyByProjectId(projectId);
                    response.setCompany(company);
                    break;
                case 3:
                    // 获取推荐人信息
                    String introductors = projectMetadataMapper.getIntroductorsByProjectId(projectId);
                    response.setIntroductors(introductors);
                    break;
                default:
                    // 处理其他可能的风格值
                    break;
            }
        }

        return response;
    }

    // 获取详细介绍
    public ProjectdetailsIntroduceResponse getProjectIntroduce(Long projectId) {
        ProjectMetadata projectMetadata = projectMetadataMapper.getdetialProjectItroduce(projectId);

        ProjectdetailsIntroduceResponse response = new ProjectdetailsIntroduceResponse();

        // 设置公共字段
        response.setIntroduction(projectMetadata.getIntroduction());

        Integer projectStyle = projectMetadata.getProjectStyle();

        // 根据 projectStyle 填充不同的字段
        if (projectStyle != null) {
            switch (projectStyle) {
                case 1:
                    // 获取 imageIds
                    List<Long> imageIds = projectConnectImageMapper.getImageIdsByProjectId(projectId);

                    if (imageIds == null || imageIds.isEmpty()) {
                        System.out.println("No image IDs found for project ID: " + projectId);
                    } else {
                        System.out.println("Found image IDs: " + imageIds);
                    }

                    // 使用 imageIds 获取项目图片
                    List<String> projectImages = imageIds.stream()
                            .map(imageId -> {
                                String imagePath = innovationPlazaImageMapper.selectById(imageId).getImage();
                                if (imagePath == null || imagePath.isEmpty()) {
                                    System.out.println("Empty or null image path for image ID: " + imageId);
                                    return null;
                                }
                                return imagePath;
                            })
                            .filter(Objects::nonNull)
                            .map(imageRelativePath -> {
                                String url = ossService.getFileUrl(imageRelativePath);
                                if (url == null) {
                                    System.out.println("Generated URL is null for path: " + imageRelativePath);
                                }
                                return url;
                            })
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());

                    response.setProjectImages(projectImages);
                    response.setInnovation(projectMetadata.getInnovation());
                    break;
                case 2:
                    response.setDirectionField(projectMetadata.getDirectionField());
                    response.setDirectionTechnical(projectMetadata.getDirectionTechnical());
                    response.setResources(projectMetadata.getResources());
                    response.setSubmissionMaterials(projectMetadata.getSubmissionMaterials());
                    response.setEvaluationMethod(projectMetadata.getEvaluationMethod());
                    response.setSupportMatching(projectMetadata.getSupportMatching());
                    response.setSupportPolicy(projectMetadata.getSupportPolicy());
                    break;
                case 3:
                    response.setIconicResults(projectMetadata.getIconicResults());
                    response.setChallenge(projectMetadata.getChallenge());
                    response.setUndergraduatesAchievement(projectMetadata.getUndergraduatesAchievement());
                    break;
                default:
                    // 处理其他可能的风格值
                    break;
            }
        }

        return response;
    }

    /*//获取详细页面的基础元信息
    public ProjectdetailsMetaResponse getProjectDetailsMeta(BigInteger projectId) {
        ProjectdetailsMetaResponse response = new ProjectdetailsMetaResponse();

        // 获取项目名称
        String projectName = projectMetadataMapper.getProjectNameById(projectId);
        response.setName(projectName);

        // 获取项目标签
        List<String> tags = innovationTagsMapper.getTagsByProjectId(projectId);
        response.setTags(tags);

         获取参与人图片
        List<byte[]> userImages = userMetadataMapper.getUserImagesByProjectId(projectId);
        response.setUserImages(userImages);*//*

        return response;
    }*/

    /*//获取详细介绍
    public ProjectdetailsIntroduceResponse getProjectIntroduce(BigInteger projectId) {
        ProjectMetadata projectMetadata = projectMetadataMapper.getProjectItroduce(projectId);
        List<byte[]> projectImages = projectConnectImageMapper.getImagesByProjectId(projectId);

        ProjectdetailsIntroduceResponse response = new ProjectdetailsIntroduceResponse();
        response.setIntroduction(projectMetadata.getIntroduction());
        response.setInnovation(projectMetadata.getInnovation());
        response.setProjectImages(projectImages);

        return response;
    }*/
    //获取项目成员
    public List<ProjectUser> getProjectMembers(Long projectId) {
        return projectUserMapper.getProjectMembersByProjectId(projectId);
    }
    //
//    public ProjectResponse getProjectDetails(BigInteger projectId) {
//        InnovationPlaza innovationPlaza = innovationPlazaMapper.selectById(projectId);
//        ProjectMetadata projectMetadata = projectMetadataMapper.selectById(projectId);
//
//        List<ProjectConnectImage> projectConnectImages = projectConnectImageMapper.selectList(
//                new QueryWrapper<ProjectConnectImage>().eq("project_id", projectId)
//        );
//
//        List<byte[]> userImages = new ArrayList<>();
//        List<byte[]> projectImages = new ArrayList<>();
//
//        for (ProjectConnectImage connectImage : projectConnectImages) {
//            InnovationPlazaImage image = innovationPlazaImageMapper.selectById(connectImage.getImageId());
//            projectImages.add(image.getImage());
//        }
//
//        ProjectResponse response = new ProjectResponse();
//        response.setProjectId(innovationPlaza.getProjectId());
//        response.setName(projectMetadata.getName());
//        response.setDescription(projectMetadata.getDescription());
//        response.setIntroduction(projectMetadata.getIntroduction());
//        response.setAdvertise(projectMetadata.getAdvertise());
//        response.setInnovation(projectMetadata.getInnovation());
//        response.setLikeNum(projectMetadata.getLikeNum());
//        response.setShareNum(projectMetadata.getShareNum());
//        response.setLookNum(projectMetadata.getLookNum());
//        response.setCreatedTime(projectMetadata.getCreatedTime());
//        response.setImage(projectMetadata.getProjectImage());
//        response.setUserImages(userImages);
//        response.setProjectImages(projectImages);
//
//        return response;
//    }
    //点赞按钮curd
    @Transactional//保证方法的事务执行 ，避免多步操作时出现数据不一致
    public String toggleLike(Long projectId, String userId) {
        int count = userLikeMapper.countUserLike(projectId, userId);
        if (count > 0) {
            userLikeMapper.deleteUserLike(projectId, userId);
            projectMetadataMapper.decrementLikeNum(projectId);
            return "取消点赞";
        } else {
            userLikeMapper.insertUserLike(projectId, userId);
            projectMetadataMapper.incrementLikeNum(projectId);
            return "成功点赞";
        }
    }
    //项目浏览状态更新
    public boolean incrementClickNum(Long projectId) {
        return projectMetadataMapper.incrementClickNum(projectId) > 0;
    }
    //项目分享更新
    public boolean incrementShareNum(Long projectId) {
        return projectMetadataMapper.incrementShareNum(projectId) > 0;
    }

    //基于关键词对标题的模糊查询：快一次查询
    public List<ProjectResponse> searchProjectsByName(String sentence,String sortBy) {
        List<ProjectResponse> allProjects = getAllProjectMeta(sortBy);
        return allProjects.stream()
                .filter(project -> project.getName() != null && project.getName().contains(sentence))
                .collect(Collectors.toList());
    }
    public IPage<ProjectResponse> searchProjectsByNamePage(String sentence, String sortBy, int pageNum, int pageSize) {
        // 创建分页对象
        Page<ProjectResponse> page = new Page<>(pageNum, pageSize);

        // 查询项目元数据并分页
        IPage<ProjectResponse> projectResponsesPage = projectMetadataMapper.getAllProjectMetaPage(page);

        List<ProjectResponse> projectResponses = projectResponsesPage.getRecords();

        // 获取每个项目的标签并设置
        for (ProjectResponse projectResponse : projectResponses) {
            List<String> tags = innovationTagsMapper.getTagsByProjectId(projectResponse.getProjectId());
            projectResponse.setTags(tags);
        }

        // 根据sortBy参数进行排序
        if (sortBy != null) {
            switch (sortBy.toLowerCase()) {
                case "createdTime":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getCreatedTime).reversed());
                    break;
                case "likenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLikeNum).reversed());
                    break;
                case "sharenum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getShareNum).reversed());
                    break;
                case "looknum":
                    projectResponses.sort(Comparator.comparing(ProjectResponse::getLookNum).reversed());
                    break;
                default:
                    break;
            }
        }

        // 进行模糊查询过滤
        List<ProjectResponse> filteredProjects = projectResponses.stream()
                .filter(project -> project.getName() != null && project.getName().contains(sentence))
                .collect(Collectors.toList());

        // 将过滤后的数据设置回分页对象中
        page.setRecords(filteredProjects);
        page.setTotal(filteredProjects.size());

        return page;
    }
    //插入项目信息
    @Transactional
    public boolean saveProject(ProjectResponse projectData) {
        // 插入 InnovationPlaza 以生成 projectId
        InnovationPlaza innovationPlaza = new InnovationPlaza();
        innovationPlaza.setProjectType(InnovationPlaza.ProjectType.project);
        innovationPlazaMapper.insert(innovationPlaza);

        Long projectId = innovationPlaza.getProjectId();
        // 插入项目元数据
        ProjectMetadata projectMetadata = new ProjectMetadata();
        projectMetadata.setProjectId(projectId);
        projectMetadata.setName(projectData.getName());
        projectMetadata.setDescription(projectData.getDescription());
//        projectMetadata.setLikeNum(projectData.getLikeNum());
//        projectMetadata.setShareNum(projectData.getShareNum());
//        projectMetadata.setLookNum(projectData.getLookNum());
//        projectMetadata.setCreatedTime(projectData.getCreatedTime());
        projectMetadata.setProjectImage(projectData.getImage());
        projectMetadata.setIntroduction(projectData.getIntroduction());
        projectMetadata.setAdvertise(projectData.getAdvertise());
        projectMetadata.setInnovation(projectData.getInnovation());

        int metadataResult = projectMetadataMapper.insert(projectMetadata);
        if (metadataResult == 0) {
            return false;
        }

        // 插入标签
        for (String tag : projectData.getTags()) {
            InnovationTags innovationTag = new InnovationTags();
            innovationTag.setName(tag);
            innovationTag.setTagType("project");
            innovationTagsMapper.insert(innovationTag);

            InnovationConnectTags connectTags = new InnovationConnectTags();
            connectTags.setProjectId(projectId);
            connectTags.setTagId(innovationTag.getTagId());
            innovationConnectTagsMapper.insert(connectTags);
        }

        // 插入项目图片
        for (String image : projectData.getProjectImages()) {
            InnovationPlazaImage plazaImage = new InnovationPlazaImage();
            plazaImage.setImage(image);
            innovationPlazaImageMapper.insert(plazaImage);

            ProjectConnectImage connectImage = new ProjectConnectImage();
            connectImage.setProjectId(projectId);
            connectImage.setImageId(plazaImage.getImageId());
            projectConnectImageMapper.insert(connectImage);
        }

        return true;
    }
    //基于关键词对标题的模糊查询：慢，多次查询
//    public List<ProjectResponse> searchProjectsByName(String name) {
//        List<ProjectMetadata> projectMetadataList = projectMetadataMapper.selectList(
//                new QueryWrapper<ProjectMetadata>().like("name", name)
//        );
//
//        List<ProjectResponse> responses = new ArrayList<>();
//        for (ProjectMetadata projectMetadata : projectMetadataList) {
//            BigInteger projectId = projectMetadata.getProjectId();
//            responses.add(getProjectOverview(projectId));//获取满足模糊查询的projectid对应的project
//        }
//
//        return responses;
//    }
    //根据ID连表查询项目概览
//    private ProjectResponse getProjectOverview(BigInteger projectId) {
//        InnovationPlaza innovationPlaza = innovationPlazaMapper.selectById(projectId);
//        ProjectMetadata projectMetadata = projectMetadataMapper.selectById(projectId);
//
//        List<InnovationConnectTags> connectTags = innovationConnectTagsMapper.selectList(
//                new QueryWrapper<InnovationConnectTags>().eq("project_id", projectId)
//        );
//
//        List<String> tags = new ArrayList<>();
//        for (InnovationConnectTags connectTag : connectTags) {
//            InnovationTags tag = innovationTagsMapper.selectById(connectTag.getTagId());
//            tags.add(tag.getName());
//        }
//
//        ProjectResponse response = new ProjectResponse();
//        response.setProjectId(innovationPlaza.getProjectId());
//        response.setName(projectMetadata.getName());
//        response.setTags(tags);
//        response.setDescription(projectMetadata.getDescription());
//        response.setIntroduction(projectMetadata.getIntroduction());
//        response.setAdvertise(projectMetadata.getAdvertise());
//        response.setInnovation(projectMetadata.getInnovation());
//        response.setLikeNum(projectMetadata.getLikeNum());
//        response.setShareNum(projectMetadata.getShareNum());
//        response.setLookNum(projectMetadata.getLookNum());
//        response.setCreatedTime(projectMetadata.getCreatedTime());
//        response.setImage(projectMetadata.getProjectImage());
//
//        return response;
//    }

    //    public List<ProjectResponse> getAllProjectDetails(String sortBy) {
//        QueryWrapper<ProjectMetadata> queryWrapper = new QueryWrapper<>();
//
//        if ("createdTime".equalsIgnoreCase(sortBy)) {
//            queryWrapper.orderByDesc("created_time");
//        } else if ("likeNum".equalsIgnoreCase(sortBy)) {
//            queryWrapper.orderByDesc("like_num");
//        } else if ("shareNum".equalsIgnoreCase(sortBy)) {
//            queryWrapper.orderByDesc("share_num");
//        } else if ("lookNum".equalsIgnoreCase(sortBy)) {
//            queryWrapper.orderByDesc("look_num");
//        }
//
//        List<ProjectMetadata> projectMetadataList = projectMetadataMapper.selectList(queryWrapper);
//
//        List<ProjectResponse> responses = new ArrayList<>();
//        for (ProjectMetadata projectMetadata : projectMetadataList) {
//            BigInteger projectId = projectMetadata.getProjectId();
//            responses.add(getProjectDetails(projectId));
//        }
//
//        return responses;
//    }
}
